package com.jt.controller;

import com.alibaba.dubbo.common.json.JSON;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.jt.pojo.User;
import com.jt.service.UserService;
import com.jt.util.ObjectMapperUtil;
import com.jt.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisCluster;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/user/")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JedisCluster jedisCluster;

    @RequestMapping("/findUser")
    public List<User> findUser(){
        List<User> list = userService.findUser();
        String json= ObjectMapperUtil.toJson(list);
        return list;
    }

    /**
     * 需求分析:
     *  校验用户数据是否可用
     *  url:http://sso.jt.com/user/check/{param}/{type}
     *  参数:type  param
     *  返回结果:SysResult对象
     */
    @RequestMapping("check/{param}/{type}")
    public JSONPObject checkUser(@PathVariable String param, @PathVariable Integer type,String callback){
        //根据信息查询数据库获取响应记录
        Boolean flag = userService.checkUser(param,type);
        return new JSONPObject(callback,SysResult.success(flag));
    }

    /**
     *测试httpClient实现业务查询用户信息
     * url:http://www.jt.com/findUserById/7
     * 参数:7
     * 返回对象:user对象
     */
    @RequestMapping("findUserById/{userId}")
    public User findUserById(@PathVariable Long userId){
        return  userService.findUserById(userId);
    }

    @RequestMapping("query/{ticket}")
    public JSONPObject findUserByTicker(@PathVariable String ticket, HttpServletResponse response,String callback){
        if(jedisCluster.exists(ticket)){
            //可以正确返回
            String userJson = jedisCluster.get(ticket);
            return new JSONPObject(callback,SysResult.success(userJson));
        }else {
            //如果根据ticket查询有误则删除ticket信息
            Cookie cookie = new Cookie("JT_TICKET","");
            cookie.setDomain("jt.com");
            cookie.setPath("/");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            return new JSONPObject(callback,SysResult.fail());
        }
    }
}
